//
//  HMAllOrdersView.swift
//  ServiceHelper
//
//  Created by Xuedan on 15/11/3.
//  Copyright © 2015年 Stan Wu. All rights reserved.
//

import UIKit
import AVFoundation


protocol SHAllOrdersDelegate{
    func allOrdesUpdated(order: NSDictionary?)
    func showSelectedTakeCarPerson()
    func hiddenTakeCarPerson()
    
    func thePreviousStepClick(number:NSNumber?)
    func theNectStepClick(number:NSNumber?)
    func hideOrderDetailView(number:NSNumber?)
}

class HMAllOrdersView: UIView ,UITableViewDelegate,UITableViewDataSource,SWImageViewDelegate,UIPopoverControllerDelegate,AVAudioPlayerDelegate,UIAlertViewDelegate,UIActionSheetDelegate {

    var vDetail:UIView!
    var tvList:UITableView!
    var pop: UIPopoverController!
    var player: AVAudioPlayer?
    var btnPlay: UIButton!
    var btnSelected:UIButton!
    var btnMore:UIButton!
    var btnReset:UIButton!
    
    var vFooterBG:UIView!
   
    var selectedDate: NSDate?
    
    var strNew :NSString!
     var strOrderId :NSString!
    var strOrderStatus :NSString!
    var orderType :NSString!
    
    var strShowType :NSString!
    var lblOrderNumber :UILabel!
    var lblOrderStatus :UILabel!
    var lblNotificationTime :UILabel!
    var btnShowDetail:UIButton!
    
    var indexNumber: NSNumber!
     var isFromNotification: Bool?
    
    var number :NSNumber?{
        didSet{
             indexNumber = number
        }
       
    }
    var strType: NSString?{
        didSet{
            
            strShowType = strType
        }
    }
    var str: NSString?{
        didSet{
            strNew = str!
            switch strNew{
            case "全部订单":break

//                btnSelected.setTitle("返回", forState: .Normal)
//                btnReset.setTitle("选取取车员", forState: .Normal)
            case "等待确认":break
//                btnSelected.setTitle("返回", forState: .Normal)
//                btnReset.setTitle("选取取车员", forState: .Normal)
            default:
                break
                
            }
        }
    }
    
    var allOrdersInfo: NSDictionary?{
        didSet{
            if allOrdersInfo != nil{
                tvList.hidden = false
            }else{
                tvList.hidden = true
            }
            
            
            if isFromNotification == true {
//                strOrderStatus = self.allOrdersInfo?.objectForKey("order_info")?.objectForKey("order_status") as? String!
//                orderType = self.allOrdersInfo?.objectForKey("order_info")?.objectForKey("pick_type") as? String!
                
                strOrderStatus = self.allOrdersInfo?.objectForKey("order_status") as? String!
                orderType = self.allOrdersInfo?.objectForKey("pick_type") as? String!

            }else{
                
                if self.allOrdersInfo != nil{
                    strOrderStatus = self.allOrdersInfo?.objectForKey("order_status") as? String!
                    orderType = self.allOrdersInfo?.objectForKey("pick_type") as? String!
                    let ary = allOrdersInfo?.objectForKey("status_detail")
                    let idx = (ary?.count)!-1
                    if ary?.count > 0{
                        lblOrderStatus?.text = ary?[(Int)(idx)].objectForKey("head") as? String!
                    }
                    
                    let orderStatus =  strOrderStatus.intValue
                    
                    switch orderStatus{
                    case 1:
                        btnSelected.setTitle("返回", forState: .Normal)
                        btnSelected.hidden = true
                        btnReset.setTitle("确认", forState: .Normal)
                        btnReset.hidden = false
                        vFooterBG.hidden = false
                        btnReset.frame = CGRectMake(237, 15, 250, 45)
                        tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64-75)
                    case 2:
                        btnSelected.setTitle("确认", forState: .Normal)
                        btnReset.setTitle("变更订单", forState: .Normal)
                        btnSelected.hidden = true
                        btnReset.hidden = true
                        vFooterBG.hidden = true
                        tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64)
                    case 3:
                        btnSelected.setTitle("返回", forState: .Normal)
                        btnSelected.hidden = true
                        if orderType == "1"{
                            btnReset.setTitle("开始服务", forState: .Normal)
                            btnReset.hidden = false
                            vFooterBG.hidden = false
                            btnReset.frame = CGRectMake(237, 15, 250, 45)
                            tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64-75)
                        }else{
                            btnReset.setTitle("选取取车员", forState: .Normal)
                            btnReset.hidden = false
                            vFooterBG.hidden = false
                            btnReset.frame = CGRectMake(237, 15, 250, 45)
                            tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64-75)
                        }
                        
                    case 4://服务已完成，待付款
                        btnSelected.setTitle("返回", forState: .Normal)
                        btnSelected.hidden = true
                        let backType = self.allOrdersInfo?.objectForKey("back_type") as? String!
                        if ((orderType == "1") || (backType == "1")){
                            btnReset.setTitle("已付款,待评价", forState: .Normal)
                            btnReset.hidden = true
                            btnReset.frame = CGRectMake(237, 15, 250, 45)
                            vFooterBG.hidden = true
                            tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64)
                            
                        }else if (backType == "2"){
                            btnReset.setTitle("选择还车员", forState: .Normal)
                            btnReset.hidden = false
                            btnReset.frame = CGRectMake(237, 15, 250, 45)
                            vFooterBG.hidden = false
                            tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64-75)
                        }
                        
                    case 5:
                        btnSelected.setTitle("确认", forState: .Normal)
                        btnReset.setTitle("变更订单", forState: .Normal)
                        btnSelected.hidden = true
                        btnReset.hidden = true
                        vFooterBG.hidden = true
                        tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64)
                    case 6:
                        btnSelected.setTitle("确认", forState: .Normal)
                        btnReset.setTitle("变更订单", forState: .Normal)
                        btnSelected.hidden = true
                        btnReset.hidden = true
                        vFooterBG.hidden = true
                        tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64)
                    case 7://已取车
                        btnSelected.setTitle("返回", forState: .Normal)
                        btnSelected.hidden = true;
                        btnReset.setTitle("已到店，开始服务", forState: .Normal)
                        btnReset.frame = CGRectMake(237, 15, 250, 45)
                        btnReset.hidden = false
                        vFooterBG.hidden = false
                        tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64-75)
                    case 8:
                        btnSelected.setTitle("返回", forState: .Normal)
                        btnSelected.hidden = true;
                        if orderType == "2"{
                            btnReset.hidden = false
                            btnReset.setTitle("服务完成", forState: .Normal)
                        }else{
                            btnReset.hidden = false
                            btnReset.setTitle("服务完成，待付款", forState: .Normal)
                        }
                        vFooterBG.hidden = false
                        tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64-75)
                        btnReset.frame = CGRectMake(237, 15, 250, 45)
                    case 9:
                        btnSelected.setTitle("返回", forState: .Normal)
                        btnReset.setTitle("开始服务", forState: .Normal)
                        btnSelected.hidden = true
                        let backType = self.allOrdersInfo?.objectForKey("back_type") as? String!
                        if orderType == "2"{
                            btnReset.hidden = true
                            btnReset.setTitle("服务完成，待选择还车方式", forState: .Normal)
                            vFooterBG.hidden = true
                            btnReset.frame = CGRectMake(237, 15, 250, 45)
                            tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64)
                            
                        }else if backType == "1"{
                            btnReset.hidden = false
                            btnReset.setTitle("确认付款", forState: .Normal)
                            vFooterBG.hidden = false
                            btnReset.frame = CGRectMake(237, 15, 250, 45)
                            tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64-75)
                        }else{
                            btnSelected.setTitle("", forState: .Normal)
                            btnReset.setTitle("", forState: .Normal)
                            btnSelected.hidden = true
                            btnReset.hidden = true
                            vFooterBG.hidden = true
                            tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64)
                        }
                        
                        
                    case 10:
                        btnSelected.setTitle("返回", forState: .Normal)
                        btnSelected.hidden = true;
                        btnSelected.hidden = true
                        
                        btnReset.hidden = false
                        btnReset.setTitle("确认付款", forState: .Normal)
                        vFooterBG.hidden = false
                        btnReset.frame = CGRectMake(237, 15, 250, 45)
                        tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64-75)
                        
                        
                    case 11:
                        btnSelected.setTitle("确认", forState: .Normal)
                        btnReset.setTitle("变更订单", forState: .Normal)
                        btnSelected.hidden = true
                        btnReset.hidden = true
                        tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64)
                        
                    case 12:
                        btnSelected.setTitle("确认", forState: .Normal)
                        btnReset.setTitle("变更订单", forState: .Normal)
                        btnSelected.hidden = true
                        btnReset.hidden = true
                        vFooterBG.hidden = true
                        tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64)
                    case 13:
                        btnSelected.setTitle("确认", forState: .Normal)
                        btnReset.setTitle("变更订单", forState: .Normal)
                        btnSelected.hidden = true
                        btnReset.hidden = true
                        vFooterBG.hidden = true
                        tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64)
                    case 14:
                        btnSelected.setTitle("确认", forState: .Normal)
                        btnReset.setTitle("确认", forState: .Normal)
                        btnSelected.hidden = true;
                        btnReset.hidden = false
                        btnReset.frame = CGRectMake(237, 15, 250, 45)
                        vFooterBG.hidden = false
                        tvList.frame = CGRectMake(0, 0, frame.size.width, frame.size.height-64-75)
                        
                    default:
                        break
                        
                    }


                }
            }
            
            
           
            
            if let audio = allOrdersInfo?.objectForKey("audio") as! String!{
                SWUtils.RunOnBackgroundThread({ () -> Void in
                    autoreleasepool({ () -> () in
                        let filename = audio.lastPathComponent
                        var data: NSData?
                        if NSFileManager.defaultManager().fileExistsAtPath(filename.temporaryPath()){
                            data = NSData(contentsOfFile: filename.temporaryPath())
                        }else{
                            data = NSData(contentsOfURL: NSURL(string: audio)!)
                            data?.writeToFile(filename.temporaryPath(), atomically: false)
                        }
                        
                        if data != nil{
                            if self.player != nil{
                                self.player!.stop()
                            }
                            
                            self.player = try? AVAudioPlayer(data: data!)
                            self.player?.delegate = self
                            self.player?.prepareToPlay()
                            SWUtils.RunOnMainThread({ () -> Void in
                                self.tvList.reloadData()
                            })
                        }
                        
                    })
                })
                
            }else{
                if self.player != nil{
                    self.player!.stop()
                }
                
                self.player = nil
                
            }
            
            btnPlay?.selected = false
            tvList.reloadData()
            updateAllOrdersInfo()
        }
        
    }
    
    var allOrdersDelegate: SHAllOrdersDelegate?
    
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
    // Drawing code
    }
    */
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        tvList = UITableView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height-64-75))
        tvList.delegate = self
        tvList.dataSource = self
        tvList.backgroundColor = UIColor.whiteColor()
        tvList.separatorStyle = .None
         self.addSubview(tvList)
//        var vLine3 = UIView (frame: CGRectMake(0 , 620,  frame.size.width, 1))
//        vLine3.backgroundColor = UIColor(white: 0.90, alpha: 1)
//        vDetail.addSubview(vLine3)
        
        
        vFooterBG = UIView.init(frame: CGRectMake(0, frame.size.height-75-64, frame.size.width, 75))
        vFooterBG.backgroundColor = UIColor.whiteColor()
        vFooterBG.layer.shadowColor = UIColor.blackColor().CGColor
        vFooterBG.layer.shadowRadius = 1
        vFooterBG.layer.shadowOffset = CGSizeMake(-2, 0)
        vFooterBG.layer.shadowOpacity = 0.1
        vFooterBG.hidden = true
        self.addSubview(vFooterBG)
        
        btnSelected = UIButton(type: .Custom)
        btnSelected.frame = CGRectMake(70, 15, 250, 45)
        btnSelected.setBackgroundImage(UIImage.colorImage(UIColor(red: 0.95, green: 0.96, blue: 0.97, alpha: 1), size: CGSizeMake(1, 1)), forState: .Normal)
        btnSelected.setTitle("返回", forState: .Normal)
        btnSelected.titleLabel?.font = UIFont.systemFontOfSize(18)
        btnSelected.setTitleColor(UIColor.blackColor(), forState:.Normal)
        btnSelected.addTarget(self, action: #selector(HMAllOrdersView.startButtonClicked(_:)), forControlEvents: .TouchUpInside)
        btnSelected.clipsToBounds = true
        btnSelected.layer.cornerRadius = 4
        btnSelected.layer.borderWidth = 0.5
        btnSelected.layer.borderColor = UIColor(red: 0, green: 0.42, blue: 0.85, alpha: 1).CGColor
        vFooterBG.addSubview(btnSelected)
        btnSelected.tag = 1010
        
        btnReset = UIButton(type: .Custom)
        btnReset.frame = CGRectMake(385, 15, 250, 45)
        btnReset.setBackgroundImage(UIImage.colorImage(UIColor(red: 0.95, green: 0.96, blue: 0.97, alpha: 1), size: CGSizeMake(1, 1)), forState: .Normal)
        btnReset.setBackgroundImage(UIImage.colorImage(UIColor(red: 0.31, green: 0.61, blue: 0.84, alpha: 1), size: CGSizeMake(1, 1)), forState: .Normal)
        btnReset.setTitle("预约变更", forState: .Normal)
        btnReset.titleLabel?.font = UIFont.systemFontOfSize(18)
        btnReset.setTitleColor(UIColor.whiteColor(), forState:.Normal)
        btnReset.addTarget(self, action: #selector(HMAllOrdersView.startButtonClicked(_:)), forControlEvents: .TouchUpInside)
        btnReset.clipsToBounds = true
        btnReset.layer.cornerRadius = 4
        btnReset.layer.borderWidth = 0.5
        btnReset.layer.borderColor = UIColor(white: 0.53, alpha: 1).CGColor
        vFooterBG.addSubview(btnReset)
        btnReset.tag = 1011
        
       
        
        
        self.refreshData()
    }
    
    func refreshData(){
        allOrdersDelegate?.allOrdesUpdated(allOrdersInfo)
    }
    
    func startButtonClicked(sender:UIButton){
        NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: #selector(HMAllOrdersView.confirmClicked(_:)), object: sender)
        self.performSelector(#selector(HMAllOrdersView.confirmClicked(_:)), withObject: sender, afterDelay: 0.5)
    }

    func confirmClicked(sender:UIButton){
        switch sender.tag{
        case 100:
            print("100")
           allOrdersDelegate?.thePreviousStepClick(indexNumber)
            
        case 101:
            print("101")
            allOrdersDelegate?.theNectStepClick(indexNumber)
        case 102:
                self.showActionSheet(sender)
//            self.adjustClicked(sender)
        case 1010:
            print("1010")
            
            
        case 1011:
            print("1011")
            let orderStatus =  strOrderStatus.intValue
            let orderType = self.allOrdersInfo?.objectForKey("pick_type") as! String!
            
            switch orderStatus{
            case 1:
                self.confirmClicked()
            case 2: break
//                self.adjustClicked(sender)
            case 3:
                
                if orderType == "2"{
                     allOrdersDelegate?.showSelectedTakeCarPerson()
                }else{
                    self.startService()
                }
               
//                allOrdersDelegate?.hideOrderDetailView(indexNumber)
            case 4:
                
            if ((allOrdersInfo?.objectForKey("sendcar_info")) != nil){
                allOrdersDelegate?.showSelectedTakeCarPerson()
            }else{
                 break
            }
               
                
            case 5:break
                
            case 6:break
                
            case 7://已取车
                self.startService()
            case 8://开始服务
                if orderType == "2"{
//                    self.endService()

                   allOrdersDelegate?.hiddenTakeCarPerson()
                }else{
//                     self.endService()
                      allOrdersDelegate?.hiddenTakeCarPerson()
                }
               
            case 9:
                
               if sender.titleLabel?.text == "确认付款"{
                     self.alreadyPay()
                }
                
            case 10:
//                allOrdersDelegate?.showSelectedTakeCarPerson()
//                allOrdersDelegate?.hideOrderDetailView(indexNumber)
                if sender.titleLabel?.text == "确认付款"{
                    self.alreadyPay()
                }
            case 11:break
            case 12:break
            case 13:break
            case 14:
                self.confirmClicked()
                
            default:
                break
                
            }

//            allOrdersDelegate?.showSelectedTakeCarPerson()
        case 1000:
            print("1000")
            allOrdersDelegate?.hiddenTakeCarPerson()
        case 1002:
            print("1002")
             allOrdersDelegate?.showSelectedTakeCarPerson()
        case 103:
            print("103")
            strShowType = "1"
            tvList.reloadData()
        case 104:
            print("104")
            strShowType = "2"
            tvList.reloadData()
            
        default:()
            
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UIActionSheet Delegate
    func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {
        
        if buttonIndex >= 0 {
            let buttonTitle = actionSheet.buttonTitleAtIndex(buttonIndex)
            if buttonTitle=="变更订单"{
                self.adjustClicked()
            }else if buttonTitle == "取消订单"{
                self.cancleOrder()
            }else{
                return
            }
            
        }
        
    }
    
    func showActionSheet(sender:UIButton){
        
        let aryStatusDetail = self.allOrdersInfo?.objectForKey("status_detail")
        let aryActionButtons = NSMutableArray()
        let status = NSMutableArray()
        
         for i in 0 ..< aryStatusDetail!.count{
            let dic = aryStatusDetail?.objectAtIndex(i) as! NSDictionary
            let orderStatus = dic.objectForKey("status")
            status.addObject(orderStatus!)
         }
        
        if status.indexOfObject("14") == NSNotFound{
            let index = aryActionButtons.indexOfObject("变更订单")
            if index == NSNotFound {
                aryActionButtons.addObject("变更订单")
            }
        }
        
        if status.indexOfObject("13") == NSNotFound{
            let index = aryActionButtons.indexOfObject("取消订单")
            if index == NSNotFound {
                aryActionButtons.addObject("取消订单")
            }
        }
        
        if aryActionButtons.count > 0 {
            let actionSheet = UIActionSheet()
            actionSheet.title = "选择要进行的操作"
            actionSheet.delegate = self
            for j in 0 ..< aryActionButtons.count{
                [actionSheet .addButtonWithTitle(aryActionButtons.objectAtIndex(j) as? String)]
            }
//            actionSheet.addButtonWithTitle("变更订单")
//            actionSheet.addButtonWithTitle("取消订单")
            actionSheet.addButtonWithTitle("取消")
            //        var actionSheet = UIActionSheet(title: "选择要进行的操作", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles:nil)
            //        actionSheet.addButtonWithTitle("注销")
            actionSheet.showFromRect(sender.frame, inView: self, animated: true)
        }
        
        
    }
    
    
    func updateButtonStatus(){
//        if let status = allOrdersInfo?.objectForKey("order_status")?.intValue{
//            if 1==status{
//                for i in 0 ..< 3{
//                    let btn = self.viewWithTag(1000+i)
//                    btn?.hidden = false
//                }
//            }else{
//                for i in 0 ..< 3{
//                    let btn = self.viewWithTag(1000+i)
//                    btn?.hidden = true
//                }
//            }
//        }else{
//            for i in 0 ..< 3{
//                let btn = self.viewWithTag(1000+i)
//                btn?.hidden = true
//            }
//        }
        
        self.tvList.reloadData()
        allOrdersDelegate?.allOrdesUpdated(allOrdersInfo)
    }
    
    
    //获取最新订单详情
    func getNewOrderDetail(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                if let order_id = self.allOrdersInfo?.objectForKey("order_id") as! String!{
                    let dict = SHDataProvider.getOrderDetail(NSDictionary(object: order_id,forKey: "order_id"))
                    print(dict)
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                self.allOrdersInfo = NSDictionary(dictionary: (dict?.objectForKey("data"))! as! [NSObject : AnyObject])
                                self.updateAllOrdersInfo()

                            }else{
                                //                                if let msg = dict?.objectForKey("message") as? String{
                                //                                    UIAlertView.show(nil, message: msg, cancelButton: nil)
                                //                                }else{
                                //                                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                                //                                }
                            }
                        }else{
                            //                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                        //                        self.updateAllOrdersInfo()
                    })
                }
            })
        }
        
    }
    
    //确认
    func confirmClicked(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                if let order_id = self.allOrdersInfo?.objectForKey("order_id") as! String!{
                    let dict = SHDataProvider.confimOrder(NSDictionary(object: order_id,forKey: "order_id"))
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                                let mut = NSMutableDictionary(dictionary: self.allOrdersInfo!) as NSMutableDictionary
                                mut.setObject("3", forKey: "order_status")
                                
                                self.allOrdersInfo = NSDictionary(dictionary: mut)
                            }else{
                                if let msg = dict?.objectForKey("message") as? String{
                                    UIAlertView.show(nil, message: msg, cancelButton: nil)
                                }else{
                                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                                }
                            }
                        }else{
                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                         self.getNewOrderDetail()
                    })
                }
            })
        }
    }
    
    //取消订单
    func cancleOrder(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                if let order_id = self.allOrdersInfo?.objectForKey("order_id") as! String!{
                    
                    let dict = SHDataProvider.cancleOrder(["order_id":order_id,"dealer_id":SHDataProvider.getDealerID()])
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                                let mut = NSMutableDictionary(dictionary: self.allOrdersInfo!) as NSMutableDictionary
                                mut.setObject("13", forKey: "order_status")
                                
                                self.allOrdersInfo = NSDictionary(dictionary: mut)
                            }else{
                                if let msg = dict?.objectForKey("message") as? String{
                                    UIAlertView.show(nil, message: msg, cancelButton: nil)
                                }else{
                                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                                }
                            }
                        }else{
                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                        self.getNewOrderDetail()
                        
                        
                    })
                }
            })
        }
    }
    
    //开始服务
    func startService(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                if let order_id = self.allOrdersInfo?.objectForKey("order_id") as! String!{
                    let dict = SHDataProvider.startService(NSDictionary(object: order_id,forKey: "order_id"))
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                                let mut = NSMutableDictionary(dictionary: self.allOrdersInfo!) as NSMutableDictionary
                                mut.setObject("8", forKey: "order_status")
                                
                                self.allOrdersInfo = NSDictionary(dictionary: mut)
                            }else{
                                if let msg = dict?.objectForKey("message") as? String{
                                    UIAlertView.show(nil, message: msg, cancelButton: nil)
                                }else{
                                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                                }
                            }
                        }else{
                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                        self.getNewOrderDetail()
                        
                        
                    })
                }
            })
        }
    }
    
    
    //服务完成
    func endService(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                if let order_id = self.allOrdersInfo?.objectForKey("order_id") as! String!{
                    let dict = SHDataProvider.endService(["order_id":order_id,"price":"1000"])
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                                let mut = NSMutableDictionary(dictionary: self.allOrdersInfo!) as NSMutableDictionary
                                mut.setObject("4", forKey: "order_status")
                                
                                self.allOrdersInfo = NSDictionary(dictionary: mut)
                            }else{
                                if let msg = dict?.objectForKey("message") as? String{
                                    UIAlertView.show(nil, message: msg, cancelButton: nil)
                                }else{
                                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                                }
                            }
                        }else{
                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                         self.getNewOrderDetail()
                    })
                }
            })
        }
    }

    
    //确认付款
    func alreadyPay(){
        SWUtils.RunOnBackgroundThread { () -> Void in
            autoreleasepool({ () -> () in
                if let order_id = self.allOrdersInfo?.objectForKey("order_id") as! String!{
                    let dict = SHDataProvider.alreadyPay(NSDictionary(object: order_id,forKey: "order_id"))
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                                let mut = NSMutableDictionary(dictionary: self.allOrdersInfo!) as NSMutableDictionary
                                mut.setObject("12", forKey: "order_status")
                                
                                self.allOrdersInfo = NSDictionary(dictionary: mut)
                            }else{
                                if let msg = dict?.objectForKey("message") as? String{
                                    UIAlertView.show(nil, message: msg, cancelButton: nil)
                                }else{
                                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                                }
                            }
                        }else{
                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                        
                        self.getNewOrderDetail()
                        
                        
                    })
                }
            })
        }
    }

    
    
    func adjustClicked(){
        let vc = UIViewController()
        let picker = UIDatePicker()
        picker.minuteInterval = 30
        
        picker.datePickerMode = UIDatePickerMode.DateAndTime
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        
        let minday = formatter.dateFromString(formatter.stringFromDate(NSDate().dateByAddingTimeInterval(24*3600)))
        let maxday = formatter.dateFromString(formatter.stringFromDate(NSDate().dateByAddingTimeInterval(24*3600*3)))
        
        picker.minimumDate = minday?.dateByAddingTimeInterval(9*3600)
        picker.maximumDate = maxday?.dateByAddingTimeInterval(17*3600)
        picker.tag = 100
        
        picker.addTarget(self, action: #selector(HMAllOrdersView.dateChanged(_:)), forControlEvents: .ValueChanged)
        
        
        
        vc.view.addSubview(picker)
        
        pop = UIPopoverController(contentViewController: vc)
        pop.delegate = self
        pop.popoverContentSize = CGSizeMake(320, 218)
        pop.presentPopoverFromRect(btnMore.frame, inView: self, permittedArrowDirections: .Any, animated: true)
        
        
    }
    
    func dateChanged(sender: UIDatePicker){
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd";
        
        
        let baseDate = formatter.dateFromString(formatter.stringFromDate(sender.date)) as NSDate!
        
        if sender.date.timeIntervalSinceDate(baseDate.dateByAddingTimeInterval(9*3600)) >= 0 && baseDate.dateByAddingTimeInterval(17*3600).timeIntervalSinceDate(sender.date) >= 0{
            
        }else if sender.date.timeIntervalSinceDate(baseDate.dateByAddingTimeInterval(9*3600)) < 0{
            sender.date = baseDate.dateByAddingTimeInterval(9*3600)
        }else{
            sender.date = baseDate.dateByAddingTimeInterval(17*3600)
        }
        
    }


    
    //  MARK: - UITableView Delegate & Data Source
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let identifierDetail = "OrderDetail"
        let identifierStatus = "OrderStatus"
        
        if strShowType == "1"{
            var cell = tableView.dequeueReusableCellWithIdentifier(identifierDetail) as UITableViewCell!
            if cell == nil {
                cell = UITableViewCell(style: .Default, reuseIdentifier: identifierDetail)
                var lbl = UILabel.create(CGRectMake(10, 0, 80, 44), font: UIFont.systemFontOfSize(16), textColor: UIColor(white: 0.5, alpha: 1))
                lbl.tag = 100
                cell.contentView.addSubview(lbl)
                
                lbl = UILabel.create(CGRectMake(95, 0,575 , 44), font: UIFont.systemFontOfSize(16), textColor: UIColor.blackColor())
                lbl.tag = 101
                cell.contentView.addSubview(lbl)
                
                if indexPath.row == 10{
                    for i in 0 ..< 6{
                        let imgv = SWImageView(frame: CGRectMake(100+CGFloat(84*i), 0, 71, 71))
                        imgv.clipsToBounds = true
                        imgv.layer.borderWidth = 0.5
                        imgv.layer.borderColor = UIColor(red: 0.8, green: 0.82, blue: 0.85, alpha: 1).CGColor
                        imgv.layer.cornerRadius = 4
                        imgv.delegate = self
                        imgv.tag = 200+i
                        cell.contentView.addSubview(imgv)
                        
                        let btn = UIButton(type: .Custom)
                        btn.frame = imgv.bounds
                        imgv.userInteractionEnabled = true
                        btn.addTarget(self, action: #selector(HMAllOrdersView.imageClicked(_:)), forControlEvents: .TouchUpInside)
                        imgv.addSubview(btn)
                    }
                    
                    let btn = UIButton(type: .Custom)
                    btn.setBackgroundImage(UIImage(named: "OrderIconPlay"), forState: .Normal)
                    btn.setBackgroundImage(UIImage(named: "OrderIconPause"), forState: .Selected)
                    btn.sizeToFit()
                    btn.frame = CGRectMake(tvList.frame.size.width-btn.frame.size.width+10, 13, btn.frame.size.width, btn.frame.size.height)
                    btn.titleLabel?.font = UIFont.boldSystemFontOfSize(14)
                    btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
                    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0)
                    btn.tag = 300
                    btn.addTarget(self, action: #selector(HMAllOrdersView.audioClicked), forControlEvents: .TouchUpInside)
                    cell.contentView.addSubview(btn)

                }
            }
            
            let lblTitle = cell.contentView.viewWithTag(100) as! UILabel!
            let lblDetail = cell.contentView.viewWithTag(101) as! UILabel!
            
            switch indexPath.row{
            case 0:
                lblTitle.text = "预约人："
                lblDetail.text = allOrdersInfo?.objectForKey("nickname") as! String?
            case 1:
                lblTitle.text = "预约时间："
                lblDetail.text = allOrdersInfo?.objectForKey("order_time") as! String?
            case 2:
                lblTitle.text = "联系电话："
                if let phone = allOrdersInfo?.objectForKey("order_phone") as! String!{
                    lblDetail.text = phone
                }else if let phone = allOrdersInfo?.objectForKey("phone") as! String!{
                    lblDetail.text = phone
                }else{
                    lblDetail.text = nil
                }
            case 3:
                lblTitle.text = "服务方式："
                if let pickType = allOrdersInfo?.objectForKey("pick_type")?.intValue{
                    if 1==pickType{
                        lblDetail.text = "送车到店"
                    }else{
                        lblDetail.text = "上门取车"
                    }
                }else{
                    lblDetail.text = nil
                }

            case 4:
//                lblTitle.text = "取车地址："
                if let getCarAddress = allOrdersInfo?.objectForKey("getcar_info")?.objectForKey("c_address") as! String!{
                    lblTitle.text = "取车地址："
                    lblDetail.text = getCarAddress
                }else{
                    lblTitle.text = "取车地址："
                    lblDetail.text = nil
                }
                
                
                if let sendCarAddress = allOrdersInfo?.objectForKey("sendcar_info")?.objectForKey("c_address") as! String!{
                    lblDetail.text = sendCarAddress
                    lblTitle.text = "还车地址："
                }else{
                    lblDetail.text = nil
                    lblTitle.text = "还车地址："

                }
                
                
                
            case 5:
                lblTitle.text = "服务内容："
                if let content = allOrdersInfo?.objectForKey("content") as! String!{
                    lblDetail.text = content
                }else{
                    lblDetail.text = nil
                }

            case 6:
                lblTitle.text = "车辆型号："
                if let carType = allOrdersInfo?.objectForKey("car_info")?.objectForKey("series_name") as! String? {
                    lblDetail.text = carType
                }else{
                    lblDetail.text = "海马M6"
                }
//                lblDetail.text = allOrdersInfo?.objectForKey("car_info")?.objectForKey("series_name") as! String?
            case 7:
                lblTitle.text = "行驶里程："
                if let mileage = allOrdersInfo?.objectForKey("mileage") as! String!{
                    lblDetail.text = "\(mileage) KM"
                }else{
                    lblDetail.text = nil
                }
            case 8:
                lblTitle.text = "保养内容："
                if let upkeepType = allOrdersInfo?.objectForKey("upkeep_type") as! String!{
                    var ary = upkeepType.componentsSeparatedByString(",")
                    var aryName = ["机油","机油过滤器","空气滤清器","空调空气滤清器","冷却液","油滤器","燃油滤清器","火花塞","制动液","手动变速箱油","自动变速箱油","发动机正时皮带"]
                    let str = NSMutableString()
                    for i in 0 ..< ary.count{
                         let idx = ary[i]
                        
//                        var intVal:Int = idx.toint()
                       if idx != ""{
                            str.appendString(aryName[Int(idx)!])
                            str.appendString(",")
                        }
                    
                    }
                    
//                    var txt = str.replaceCharactersInRange(NSMakeRange(str.length - 1, 1), withString: "") as? String
                    let txtt = str.substringWithRange(NSMakeRange(0, str.length-1))
                    lblDetail.text = txtt
                }else{
                    lblDetail.text = nil
                }
                

            case 9:
                lblTitle.text = "维修服务内容："
                if let repairContent = allOrdersInfo?.objectForKey("content") as! String!{
                    lblDetail.text = repairContent
                }else{
                    lblDetail.text = nil
                }
            case 10:
                lblTitle.text = "图片语音："
                lblDetail.text = ""
                btnPlay = cell.contentView.viewWithTag(300) as! UIButton!
                if player != nil{
                    btnPlay.hidden = false
                    //\\
//                    let audio = allOrdersInfo?.objectForKey("audio") as! String!
                    //\\
//                    var path = audio.lastPathComponent.temporaryPath()
                    
                    
                    
                    btnPlay.setTitle(String(format: "%.0lf''", player!.duration), forState: .Normal)
                    
                }else{
                    btnPlay.hidden = true
                }
                

                let size = lblDetail.sizeThatFits(CGSizeMake(lblDetail.frame.size.width, CGFloat(FLT_MAX)))
                var frame = lblDetail.frame
                frame.size.height = size.height
                lblDetail.frame = frame
                
                let y = frame.origin.y + frame.size.height + 10
                let photoList = allOrdersInfo?.objectForKey("photo_list") as! NSArray!
                if photoList?.count > 0 {
                    for i in 0 ..< 6{
                        let imgv = cell.contentView.viewWithTag(200+i) as! SWImageView
                        frame = imgv.frame
                        frame.origin.y = y
                        imgv.frame = frame
                        if i < photoList.count{
                            imgv.hidden = false
                            imgv.loadURL(photoList[i].objectForKey("small_url") as? String)
                        }else{
                            imgv.hidden = true
                            imgv.image = nil
                        }
                    }
                }
                else{
                    
                    
                    
                    for i in 0 ..< 6{
                        let imgv = cell.contentView.viewWithTag(200+i) as! SWImageView
                        imgv.image = nil
                        imgv.hidden = true
                    }
                }

            case 11:
                lblTitle.text = "备注描述："
                if let remark = allOrdersInfo?.objectForKey("remark") as! String!{
                    lblDetail.text = remark
                }else{
                    lblDetail.text = nil
                }
            case 12:
                lblTitle.text = "取车员"

             default:()
            }
           cell.selectionStyle = UITableViewCellSelectionStyle.None
            return cell

        }
        
        var cell = tableView.dequeueReusableCellWithIdentifier(identifierStatus) as UITableViewCell!
        if cell == nil {
            cell = UITableViewCell(style: .Default, reuseIdentifier: identifierDetail)
            var lbl = UILabel.create(CGRectMake(90,30,1024-360-120,20), font: UIFont.systemFontOfSize(18), textColor: UIColor(red: 0.06, green: 0.48, blue: 0.78, alpha: 1))
            lbl.tag = 100;
            cell.contentView.addSubview(lbl);
            
            lbl = UILabel.create(CGRectMake(90,60,1024-360-120,20), font: UIFont.systemFontOfSize(18), textColor: UIColor.grayColor())
            lbl.tag = 101;
            cell.contentView.addSubview(lbl);
            
            var imgv = UIImageView.init(frame: CGRectMake(28, 30, 20, 20))
            imgv.backgroundColor = UIColor(red: 0.16, green: 0.50, blue: 0.78, alpha: 1)
            imgv.layer.cornerRadius = 10.0
            imgv.tag = 102;
            cell.contentView.addSubview(imgv)
            
            imgv = UIImageView.init(frame: CGRectMake(38, 55, 1, 45))
            imgv.backgroundColor = UIColor(red: 0.16, green: 0.50, blue: 0.78, alpha: 1)
            imgv.tag = 103;
            cell.contentView.addSubview(imgv)
            
            lbl = UILabel.create(CGRectMake(28,30,20,20), font: UIFont.systemFontOfSize(15), textColor: UIColor.whiteColor())
            lbl.textAlignment = NSTextAlignment.Center
            lbl.tag = 104;
            cell.contentView.addSubview(lbl);
            
        }
        
        let lblStatus = cell.contentView.viewWithTag(100) as! UILabel
        let lblStatusDetail = cell.contentView.viewWithTag(101) as! UILabel
        let lblNumber = cell.contentView.viewWithTag(104) as! UILabel
        
        let ary = allOrdersInfo?.objectForKey("status_detail")
        let dicStatus = ary?.objectAtIndex((ary?.count)!-indexPath.row-1)
        let head = dicStatus?.objectForKey("head") as! String!
        let date = dicStatus?.objectForKey("date")  as! String!
        let msg = dicStatus?.objectForKey("msg")  as! String!
        
        lblStatus.text = "\(head) (\(date))"
        lblStatusDetail.text = "\(msg)"
//        lblNumber.text = "\(indexPath.row+1)"
        lblNumber.text = "\((ary?.count)!-indexPath.row)"
        


//        tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
        cell.selectionStyle = UITableViewCellSelectionStyle.None

        return cell
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        if strShowType == "1"{
            
            if indexPath.row == 10{
                return 85
            }
            return 44
        }else{
            return 80
        }
        
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if strShowType == "1"{
            return 12
        }else{
            let ary = allOrdersInfo?.objectForKey("status_detail")
            if ary?.count > 0{
                 return (ary?.count)!
            }
           
            
        }
        return 0
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let v = UIView(frame: CGRectMake(0, 0, 360, 161))
        v.backgroundColor = UIColor.whiteColor()
        
        lblOrderNumber = UILabel.create(CGRectMake(29, 25, 300, 25), font: UIFont.systemFontOfSize(23), textColor: UIColor.grayColor())
//        lblTitle.text = "订单号：D1620150807001A"
        v.addSubview(lblOrderNumber)
        
        if let checkNo = allOrdersInfo?.objectForKey("check_no") as! String!{
            lblOrderNumber.text = checkNo
        }else{
            lblOrderNumber.text = nil
        }
        

        var btn = UIButton(type: .Custom)
        btn.frame = CGRectMake(530, 20, 40, 40)
        btn.setImage(UIImage(named: "left"), forState: .Normal)
        btn.addTarget(self, action: #selector(HMAllOrdersView.startButtonClicked(_:)), forControlEvents: .TouchUpInside)
        v.addSubview(btn)
        btn.hidden = true
        btn.tag = 100
        
        
        btn = UIButton(type: .Custom)
        btn.frame = CGRectMake(570, 20, 40, 40)
        btn.setImage(UIImage(named: "right"), forState: .Normal)
        btn.addTarget(self, action: #selector(HMAllOrdersView.startButtonClicked(_:)), forControlEvents: .TouchUpInside)
        v.addSubview(btn)
        btn.hidden = true
        btn.tag = 101
        
        
        btnMore = UIButton(type: .Custom)
        btnMore.frame = CGRectMake(610, 20, 40, 40)
        btnMore.setImage(UIImage(named: "other"), forState: .Normal)
        btnMore.addTarget(self, action: #selector(HMAllOrdersView.startButtonClicked(_:)), forControlEvents: .TouchUpInside)
        v.addSubview(btnMore)
        btnMore.tag = 102
        
        let orderStatus =  strOrderStatus?.intValue
        if orderStatus == 1 || orderStatus == 3  || orderStatus == 14 {
            btnMore.hidden = false
        }else{
            btnMore.hidden = true
        }
        
        lblOrderStatus = UILabel.create(CGRectMake(29, 70, 400, 25), font: UIFont.systemFontOfSize(23), textColor: UIColor(red: 0, green: 0.42, blue: 0.85, alpha: 1))
        
        let ary = allOrdersInfo?.objectForKey("status_detail")
        if ary?.count > 0{
             lblOrderStatus.text = ary!.objectAtIndex(ary!.count-1).objectForKey("head") as! String!
        }
       
        v.addSubview(lblOrderStatus)
        
        let vLine = UIView (frame: CGRectMake(0 , 121, frame.size.width, 1))
        vLine.backgroundColor = UIColor(white: 0.90, alpha: 1)
        v.addSubview(vLine)
        
        
        let vLine1 = UIView (frame: CGRectMake(0 , 160, frame.size.width, 1))
        vLine1.backgroundColor = UIColor(white: 0.90, alpha: 1)
        v.addSubview(vLine1)
        
        
        
        
        btn = UIButton(type: .Custom)
        btn.frame = CGRectMake(0, 121, frame.size.width/2.0, 40)
        btn.setTitle("订单详情", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(18)
        btn.setTitleColor(UIColor.grayColor(), forState:.Normal)
        btn.addTarget(self, action: #selector(HMAllOrdersView.startButtonClicked(_:)), forControlEvents: .TouchUpInside)
        v.addSubview(btn)
        btn.tag = 103
        
        
        btn = UIButton(type: .Custom)
        btn.frame = CGRectMake(frame.size.width/2.0, 121, frame.size.width/2.0, 40)
        btn.setTitle("订单状态", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(18)
        btn.setTitleColor(UIColor.grayColor(), forState:.Normal)
        btn.addTarget(self, action: #selector(HMAllOrdersView.startButtonClicked(_:)), forControlEvents: .TouchUpInside)
        v.addSubview(btn)
        btn.tag = 104
        
        let vLine2 = UIView (frame: CGRectMake(frame.size.width/2.0 , 123, 2, 36))
        vLine2.backgroundColor = UIColor(white: 0.90, alpha: 1)
        v.addSubview(vLine2)
        
        return v
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 161
    }
    
    
//    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//        
//        let vFooterPerson = UIView.init(frame: CGRectMake(0, 0, 270, 75))
//        vFooterPerson.backgroundColor = UIColor.whiteColor()
//        vFooterPerson.layer.shadowColor = UIColor.blackColor().CGColor
//        vFooterPerson.layer.shadowRadius = 1
//        vFooterPerson.layer.shadowOffset = CGSizeMake(-2, 0)
//        vFooterPerson.layer.shadowOpacity = 0.1
//        
//        btnSelected = UIButton(type: .Custom)
//        btnSelected.frame = CGRectMake(70, 15, 250, 45)
//        btnSelected.setBackgroundImage(UIImage.colorImage(UIColor(red: 0, green: 0.42, blue: 0.85, alpha: 1), size: CGSizeMake(1, 1)), forState: .Normal)
//        btnSelected.setTitle("返回", forState: .Normal)
//        btnSelected.titleLabel?.font = UIFont.systemFontOfSize(18)
//        btnSelected.setTitleColor(UIColor.whiteColor(), forState:.Normal)
//        btnSelected.addTarget(self, action: "confirmClicked:", forControlEvents: .TouchUpInside)
//        btnSelected.clipsToBounds = true
//        btnSelected.layer.cornerRadius = 4
//        btnSelected.layer.borderWidth = 0.5
//        btnSelected.layer.borderColor = UIColor(red: 0, green: 0.42, blue: 0.85, alpha: 1).CGColor
//        vFooterPerson.addSubview(btnSelected)
//        btnSelected.tag = 1010
//        
//        btnReset = UIButton(type: .Custom)
//        btnReset.frame = CGRectMake(385, 15, 250, 45)
//        btnReset.setBackgroundImage(UIImage.colorImage(UIColor(red: 0.95, green: 0.96, blue: 0.97, alpha: 1), size: CGSizeMake(1, 1)), forState: .Normal)
//        btnReset.setTitle("预约变更", forState: .Normal)
//        btnReset.titleLabel?.font = UIFont.systemFontOfSize(18)
//        btnReset.setTitleColor(UIColor(white: 0.53, alpha: 1), forState:.Normal)
//        btnReset.addTarget(self, action: "confirmClicked:", forControlEvents: .TouchUpInside)
//        btnReset.clipsToBounds = true
//        btnReset.layer.cornerRadius = 4
//        btnReset.layer.borderWidth = 0.5
//        btnReset.layer.borderColor = UIColor(white: 0.53, alpha: 1).CGColor
//        vFooterPerson.addSubview(btnReset)
//        btnReset.tag = 1011
//
//        
//        return vFooterPerson
//    }
//    
//    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
//        
//        return 75.0
//    }

    
    func imageClicked(sender: UIButton){
        
        
        let index = sender.superview!.tag % 100
        
        if let photoList = allOrdersInfo?.objectForKey("photo_list") as! [NSDictionary]!{
            if index < photoList.count{
                let vc = UIViewController()
                vc.view.frame = CGRectMake(0, 0, 500, 500)
                let imgv = SWImageView(frame: CGRectMake(0, 0, 500, 500))
                vc.view.addSubview(imgv)
                
                if let originalURL = photoList[index].objectForKey("original_url") as? String{
                    imgv.loadURL(originalURL)
                    //<<<<<<< HEAD
                    //
                    //                    var pop = UIPopoverController(contentViewController: vc)
                    //=======
                    pop = nil
                    pop = UIPopoverController(contentViewController: vc)
                    //>>>>>>> d50134bd0a5bcc4bec1d3d0fe719f14d79f68d95
                    pop.popoverContentSize = CGSizeMake(500, 500)
                    
                    pop.presentPopoverFromRect(sender.frame, inView: sender.superview!, permittedArrowDirections: .Any, animated: true)
                }
                
            }
        }
        
        
        
    }
    
    
    func audioClicked(){
        if let audioPlayer = player{
            if audioPlayer.playing{
                audioPlayer.stop()
                btnPlay?.selected = false
            }else{
                audioPlayer.play()
                btnPlay?.selected = true
            }
//            tvList.reloadData()
        }
    }
    
    
    func updateAllOrdersInfo(){
        if isFromNotification != true {
            allOrdersDelegate?.allOrdesUpdated(allOrdersInfo)
            
        }
        tvList.reloadData()
        
    }
    
    //  MARK: - SWImageView Delegate
    func swImageViewLoadFinished(imgv: SWImageView) {
        
    }
    //  MARK: - AVAudioPlayer Delegate
    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        btnPlay?.selected = false
    }
    
    //  MARK: - UIPopoverController Delegate
    func popoverControllerShouldDismissPopover(popoverController: UIPopoverController) -> Bool {
        return true
    }
    
    func popoverControllerDidDismissPopover(popoverController: UIPopoverController) {
        let picker: UIDatePicker = popoverController.contentViewController.view.viewWithTag(100) as! UIDatePicker
        
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        if let orderTime = allOrdersInfo?.objectForKey("order_time") as? String{
            let date = formatter.dateFromString(orderTime)
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
            
            if formatter.stringFromDate(picker.date) != formatter.stringFromDate(date!){
                selectedDate = picker.date
                
                let alert = UIAlertView(title: nil, message: "是否确定要变更预约时间？", delegate: self, cancelButtonTitle: "取消")
                alert.addButtonWithTitle("变更时间")
                alert.tag = 100
                alert.show()
            }
        }
        
    }


    // MARK: - UIAlertView Delegate
    func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
        let buttonTitle = alertView.buttonTitleAtIndex(buttonIndex)
        if buttonTitle == "变更时间"{
            SWUtils.RunOnBackgroundThread { () -> Void in
                autoreleasepool({ () -> () in
                    let dict = SHDataProvider.adjustOrder(["order_id":self.allOrdersInfo?.objectForKey("order_id") as! String!,"order_time":String(format: "%.0lf",self.selectedDate!.timeIntervalSince1970)])
                    
                    SWUtils.RunOnMainThread({ () -> Void in
                        if let code = dict?.objectForKey("code")?.intValue{
                            if code==200{
                                UIAlertView.show(nil, message: "操作成功", cancelButton: nil)
                                
                                let mut = NSMutableDictionary(dictionary: self.allOrdersInfo!) as NSMutableDictionary
                                mut.setObject("14", forKey: "order_status")
                                let formatter = NSDateFormatter()
                                formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                                mut.setObject(formatter.stringFromDate(self.selectedDate!), forKey: "order_time")
                                
                                self.allOrdersInfo = NSDictionary(dictionary: mut)
                            }else{
                                if let msg = dict?.objectForKey("message") as? String{
                                    UIAlertView.show(nil, message: msg, cancelButton: nil)
                                }else{
                                    UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                                }
                            }
                        }else{
                            UIAlertView.show(nil, message: "操作失败", cancelButton: nil)
                        }
                         self.getNewOrderDetail()
//                        self.updateAllOrdersInfo()
                    })
                    
                })
            }
        }
    }




}
